import '../public.dart';

class Validate {
  /// 验证表单数据
  /// Validate form data
  static bool validator(
    Map<dynamic, dynamic> form,
    Map<dynamic, dynamic> rules,
  ) {
    form.forEach((k, v) {
      if (rules.containsKey(k)) {
        final dynamic ruleList = rules[k];
        if (ruleList is List) {
          for (final dynamic rule in ruleList) {
            if (rule is Map) {
              validatorFnc(form[k], rule);
            }
          }
        }
      }
    });
    return true;
  }

  /// 验证单个字段
  /// Validate single field
  static bool validatorFnc(dynamic value, Map<dynamic, dynamic> rule) {
    if (rule.containsKey("required") && rule["required"] == true) {
      if (ObjectUtil.isEmpty(value)) {
        throw rule['msg']?.toString() ?? 'Field is required';
      }
    }

    if (rule.containsKey("reg") && value != null && value is String) {
      final String regExpPattern = rule['reg']?.toString() ?? '';
      if (regExpPattern.isNotEmpty) {
        final RegExp regexp = RegExp(regExpPattern);
        if (!regexp.hasMatch(value)) {
          throw rule['msg']?.toString() ?? 'Invalid format';
        }
      }
    }
    return true;
  }
}
